<template>
  <div class="card-box">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-width="100px"
      class="form__content"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="现场验收人" prop="acceptUsers">
            <el-button type="primary" @click="handleAdd"
              >添 加
              {{
                formData.acceptUsers.length > 0
                  ? `已选(${formData.acceptUsers.length})`
                  : ""
              }}</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="审批意见" prop="remarks">
            <ReFastInput @emitFastInput="emitFastInput" />
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="formData.remarks"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form__footer">
      <el-button type="primary" @click="handleSave">保 存</el-button>
      <el-button type="primary" @click="handleSubmit">提 交</el-button>
      <el-button type="primary" @click="handleTransfer">转 办</el-button>
      <el-button type="primary" @click="handleReject">驳 回</el-button>
    </div>
    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view
        v-model:dialogVisible="dialogVisible"
        :taskId="props.taskId"
        :rejectUser="preTeam.userName"
      />
    </el-dialog>
    <el-dialog
      title="转办"
      v-model="dialogVisibleTransfer"
      destroy-on-close
      width="820px"
    >
      <transfer-view
        v-model:dialogVisibleTransfer="dialogVisibleTransfer"
        :taskId="props.taskId"
      />
    </el-dialog>
    <el-dialog
      title="添加验收人员"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="formData.acceptUsers"
        @emitAddUser="emitAddUser"
      />
    </el-dialog>
    <el-dialog
      title="组织验收人员"
      v-model="commitVisible"
      destroy-on-close
      width="600px"
    >
      <div class="dialog__content">
        <div class="dialog__content--title">组织验收人员信息:</div>
        <el-row>
          <el-col :span="6" class="col-left">验收人员名单：</el-col>
          <el-col :span="16" class="col-right">
            {{ cacheNameList }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="col-left">审批意见：</el-col>
          <el-col :span="18" class="col-right"> {{ formData.remarks }}</el-col>
        </el-row>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commitVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click="handleRequest">确认</el-button> -->
          <ReButton type="primary" debounce auto-loading @click="handleRequest"
            >确认</ReButton
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import ReFastInput from "/@/components/ReFastInput/index.vue";
import { reactive, ref, defineProps, onMounted, nextTick } from "vue";
import {
  postNoticeRcpSubmit,
  postGetStorageTmpData,
  postStorageTmpData
} from "/@/api/acceptance";
// import { postUserInfo } from "/@/api/user";
import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import RejectView from "../dialog/RejectView.vue";
import TransferView from "../dialog/TransferView.vue";
import AddUser from "../dialog/AddUser.vue";
import { storageLocal } from "/@/utils/storage";

import ReButton from "/@/components/ReButton/index.vue";

// import { ElMessageBox } from "element-plus";

const router = useRouter();
const route = useRoute();
const props = defineProps({
  storageData: {
    type: Object,
    default: () => {}
  },
  recordId: {
    default: ""
  },
  taskId: {
    type: String,
    default: ""
  },
  projectTeam: {
    type: Array,
    default: () => []
  }
});

let commitVisible = ref<boolean>(false);
let dialogVisible = ref<boolean>(false);
let dialogVisibleTransfer = ref<boolean>(false); // 转办弹框
let dialogVisibleTransferAdd = ref<boolean>(false); // 添加现场验收人弹

const formRef = ref<HTMLFormElement | null>(null) as any;
const formData = reactive({
  acceptUsers: [],
  remarks: ""
});
let cacheNameList = ref("");
// 获取合同对应的负责人
// let directorObj = reactive({
//   directorA: "",
//   directorBId: "",
//   directorBName: ""
// });

let preTeam = reactive({
  userName: "",
  userId: ""
}); // 上一节点的处理人信息

let outterId = ref(null);
let effective = ref(null);

onMounted(() => {
  props.projectTeam.forEach(item => {
    if ((item as any)?.roleCode === "4") {
      preTeam.userName = (item as any)?.userName;
      preTeam.userId = (item as any)?.userId;
    }
  });
});

const formRules = {
  acceptUsers: {
    required: true,
    message: "请添加现场验收人员"
  },
  remarks: {
    required: true,
    message: "请填写审批意见",
    trigger: "change"
  }
};

// if (props.storageData?.directorA) {
//   directorObj = {
//     directorA: props.storageData.directorA,
//     directorBId: props.storageData.directorBId,
//     directorBName: props.storageData.directorBName
//   };
// }

const handleAdd = () => {
  dialogVisibleTransferAdd.value = true;
};

const emitAddUser = user => {
  formData.acceptUsers = user.idList;
  cacheNameList.value = user.nameList;
  formRef.value.clearValidate();
  dialogVisibleTransferAdd.value = false;
};

const handleSubmit = async () => {
  try {
    const isValid = await new Promise(resolve =>
      formRef.value.validate(resolve)
    );
    if (!isValid) return;
    commitVisible.value = true;
  } catch (err) {
    console.log(err);
  }
};

const handleRequest = async done => {
  try {
    if (!route.query?.instanceId) {
      return;
    }
    const { instanceId, nodeDefId, flowId } = route.query;
    const info = storageLocal.getItem("info");

    const usersStr = formData.acceptUsers
      .map(item => {
        return item.id;
      })
      .join();

    let params = {
      acceptanceRecordParamDTO: {
        acceptUsers: usersStr, // 现场验收人
        flowInfoId: flowId,
        id: props.recordId
      },
      formSubMap: {
        nodeId: nodeDefId,
        isAllAcceptance: "",
        procInstId: instanceId,
        taskId: props.taskId,
        opinion: `审批意见：${formData.remarks}`,

        assignee: usersStr // 提交下一流程处理人Id
      },
      tmpStorage: {
        nodeId: nodeDefId,
        flowId,
        taskId: props.taskId,
        handlerId: info?.userId ?? "",
        userId: info?.userId ?? "",
        valueJson: JSON.stringify({
          ...formData
        })
      }
    };

    // 根据后端要求。传一个outterId
    if (outterId.value) {
      const joinData = Object.assign(params.tmpStorage, {
        outterId: outterId.value
      });
      params.tmpStorage = joinData;
    }

    // 根据后端要求。传一个effective
    if (effective.value) {
      const joinData = Object.assign(params.tmpStorage, {
        effective: effective.value
      });
      params.tmpStorage = joinData;
    }
    console.log(params, "params");

    const { code, message } = await postNoticeRcpSubmit(params);
    if (code === 200) {
      commitVisible.value = false;
      NotifMessage.success("提交成功");
      // router.replace("/acceptance/arrival");
      handleBack();
    } else {
      NotifMessage.error(message || "提交出错，请检查");
    }
  } catch (err) {
    console.log(err);
  } finally {
    setTimeout(() => {
      done();
    }, 1000);
  }
};

const handleTransfer = () => {
  dialogVisibleTransfer.value = true;
};

const handleReject = () => {
  dialogVisible.value = true;
};

const handleSave = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  const info = storageLocal.getItem("info");
  const copyFormData = JSON.parse(JSON.stringify(formData));
  const { flowId, nodeDefId } = route.query;
  // const usersStr = formData.acceptUsers
  //   .map(item => {
  //     return item.id;
  //   })
  //   .join();
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : "",
    valueJson: JSON.stringify(copyFormData)
  };

  if (outterId.value) {
    params = Object.assign(params, { outterId: outterId.value });
  }

  if (effective.value) {
    params = Object.assign(params, { effective: effective.value });
  }

  try {
    const { code, message } = await postStorageTmpData(params);
    if (code === 200) {
      NotifMessage.success("保存成功");
      // router.replace("/acceptance/arrival");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const getStorageTmpData = async () => {
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : ""
  };

  const { code, data } = await postGetStorageTmpData(params);
  if (code === 200) {
    if (data?.valueJson) {
      const { remarks, acceptUsers } = JSON.parse(data.valueJson);
      formData.remarks = remarks;
      formData.acceptUsers = acceptUsers;
      outterId.value = data.outterId;
      effective.value = data?.effective ?? "";
      // console.log(formData.acceptUsers, "formData.acceptUsers ");

      // searchUserName(acceptUsers.split(","));
      cacheNameList.value = acceptUsers
        .map(i => {
          return i.name;
        })
        .join();
    }
  }
};

const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/acceptance/arrival", replace: true });
  }
};

// 根据用户id查询用户名
// const searchUserName = async userList => {
//   if (!userList.length) return;
//   let promises = userList.map(user => {
//     return postUserInfo({ id: user });
//   });
//   let results = await Promise.all(promises);
//   const users = results.map(item => {
//     return {
//       id: (item as any)?.data.id,
//       name: (item as any)?.data.name,
//       userName: (item as any)?.data.userName
//     };
//   });

//   formData.acceptUsers = users;

//   cacheNameList.value = users
//     .map(i => {
//       return i.name;
//     })
//     .join();
// };

// 快速输入
const emitFastInput = tag => {
  formData.remarks = `${formData.remarks}${tag}`;
};

onMounted(() => {
  nextTick(() => {
    getStorageTmpData();
  });
});
</script>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .form__content {
    flex: 1;
    width: inherit;
  }
  .form__footer {
    width: inherit;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
.dialog__content {
  border: 1px solid #f0f4ff;
  border-radius: 4px;

  &--title {
    background: #f0f4ff;
    font-size: 16px;
    padding: 4px 8px;
  }
  .el-row {
    padding: 4px;
  }
  .col-left {
    text-align: right;
  }
  .col-right {
  }
}
</style>
